package org.androidpn.activity;

import java.io.IOException;
import java.util.HashMap;

import org.androidpn.HospitalClientApplication;
import org.androidpn.R;
import org.androidpn.client.Constants;
import org.androidpn.client.ServiceManager;
import org.androidpn.fragment.Fragment1;
import org.androidpn.fragment.Fragment2;
import org.androidpn.fragment.Fragment3;
import org.androidpn.fragment.Fragment4;
import org.androidpn.http.HttpApi;
import org.androidpn.listener.CommentResponseListener;
import org.androidpn.model.CTalkMessage;
import org.androidpn.model.CUserInfo;
import org.androidpn.model.NetModel;
import org.androidpn.net.BitmapUtil;
import org.androidpn.net.NetworkAgent;
import org.androidpn.net.ThreadPoolAgent;
import org.androidpn.utils.AppCache;
import org.androidpn.utils.ConstanceUtil;
import org.androidpn.utils.JsonUtil;
import org.androidpn.utils.ToastUtil;

import com.android.volley.VolleyError;

import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class MainActivity extends BaseActivity implements View.OnClickListener {

	private static final int MSG_SHOW_PROGRESS_DIALOG = 0x0100;
	private static final int MSG_HIDE_PROGRESS_DIALOG = 0x0101;
	private static final int MSG_UPDATE_USER_ICON = 0x0102;
	private LinearLayout menu1;
	private LinearLayout menu2;
	private LinearLayout menu3;
	private LinearLayout menu4;

	private ImageView iv1;
	private ImageView iv2;
	private ImageView iv3;
	private ImageView iv4;

	private TextView tv1;
	private TextView tv2;
	private TextView tv3;
	private TextView tv4;

	FragmentTransaction fragmentTransaction;
	Fragment1 fragment1;
	Fragment2 fragment2;
	Fragment3 fragment3;
	Fragment4 fragment4;

	public CUserInfo cUserInfo;

	private LinearLayout fragmentContent;

	private MainBroadcastReceiver mainBroadcastReceiver;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_main);

//		// start the service
//		ServiceManager serviceManager = new ServiceManager(this);
//		serviceManager.setNotificationIcon(R.drawable.notification);
//		serviceManager.startService();

		mainBroadcastReceiver = new MainBroadcastReceiver();
		menu1 = (LinearLayout) findViewById(R.id.menu1);
		menu2 = (LinearLayout) findViewById(R.id.menu2);
		menu3 = (LinearLayout) findViewById(R.id.menu3);
		menu4 = (LinearLayout) findViewById(R.id.menu4);
		menu1.setOnClickListener(this);
		menu2.setOnClickListener(this);
		menu3.setOnClickListener(this);
		menu4.setOnClickListener(this);
		iv1 = (ImageView) findViewById(R.id.iv1);
		iv2 = (ImageView) findViewById(R.id.iv2);
		iv3 = (ImageView) findViewById(R.id.iv3);
		iv4 = (ImageView) findViewById(R.id.iv4);

		tv1 = (TextView) findViewById(R.id.tv1);
		tv2 = (TextView) findViewById(R.id.tv2);
		tv3 = (TextView) findViewById(R.id.tv3);
		tv4 = (TextView) findViewById(R.id.tv4);

		cUserInfo = (CUserInfo) getIntent().getSerializableExtra("cuser");
		if (cUserInfo != null) {
			AppCache.getInstance().saveUserInfo(cUserInfo);
		}

		fragmentContent = (LinearLayout) findViewById(R.id.fragment_content);
		fragment1 = new Fragment1();
		fragment2 = new Fragment2();
		fragment3 = new Fragment3();
		fragment4 = new Fragment4();

		FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
		transaction.replace(R.id.fragment_content, fragment1);
		transaction.commitAllowingStateLoss();
		iv1.setBackgroundResource(R.drawable.menu1_selected);
		tv1.setTextColor(getResources().getColor(R.color.color_00CD00));

		iv2.setBackgroundResource(R.drawable.menu2);
		tv2.setTextColor(getResources().getColor(R.color.color_555555));

		iv3.setBackgroundResource(R.drawable.menu3);
		tv3.setTextColor(getResources().getColor(R.color.color_555555));

		iv4.setBackgroundResource(R.drawable.menu4);
		tv4.setTextColor(getResources().getColor(R.color.color_555555));
		

	}

	@Override
	protected void onResume() {
		cUserInfo = AppCache.getInstance().getUseInfo();
		super.onResume();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.menu_main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();

		// noinspection SimplifiableIfStatement
		if (id == R.id.action_settings) {
			return true;
		}

		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onClick(View view) {
		FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
		switch (view.getId()) {
		case R.id.menu1:
			transaction.replace(R.id.fragment_content, fragment1);
			transaction.commitAllowingStateLoss();
			iv1.setBackgroundResource(R.drawable.menu1_selected);
			tv1.setTextColor(getResources().getColor(R.color.color_00CD00));

			iv2.setBackgroundResource(R.drawable.menu2);
			tv2.setTextColor(getResources().getColor(R.color.color_555555));

			iv3.setBackgroundResource(R.drawable.menu3);
			tv3.setTextColor(getResources().getColor(R.color.color_555555));

			iv4.setBackgroundResource(R.drawable.menu4);
			tv4.setTextColor(getResources().getColor(R.color.color_555555));
			break;
		case R.id.menu2:
			transaction.replace(R.id.fragment_content, fragment2);
			transaction.commitAllowingStateLoss();

			iv1.setBackgroundResource(R.drawable.menu1);
			tv1.setTextColor(getResources().getColor(R.color.color_555555));

			iv2.setBackgroundResource(R.drawable.menu2_selected);
			tv2.setTextColor(getResources().getColor(R.color.color_00CD00));

			iv3.setBackgroundResource(R.drawable.menu3);
			tv3.setTextColor(getResources().getColor(R.color.color_555555));

			iv4.setBackgroundResource(R.drawable.menu4);
			tv4.setTextColor(getResources().getColor(R.color.color_555555));
			break;
		case R.id.menu3:
			transaction.replace(R.id.fragment_content, fragment3);
			transaction.commitAllowingStateLoss();

			iv1.setBackgroundResource(R.drawable.menu1);
			tv1.setTextColor(getResources().getColor(R.color.color_555555));

			iv2.setBackgroundResource(R.drawable.menu2);
			tv2.setTextColor(getResources().getColor(R.color.color_555555));

			iv3.setBackgroundResource(R.drawable.menu3_selected);
			tv3.setTextColor(getResources().getColor(R.color.color_00CD00));

			iv4.setBackgroundResource(R.drawable.menu4);
			tv4.setTextColor(getResources().getColor(R.color.color_555555));
			break;
		case R.id.menu4:
			transaction.replace(R.id.fragment_content, fragment4);
			transaction.commitAllowingStateLoss();

			iv1.setBackgroundResource(R.drawable.menu1);
			tv1.setTextColor(getResources().getColor(R.color.color_555555));

			iv2.setBackgroundResource(R.drawable.menu2);
			tv2.setTextColor(getResources().getColor(R.color.color_555555));

			iv3.setBackgroundResource(R.drawable.menu3);
			tv3.setTextColor(getResources().getColor(R.color.color_555555));

			iv4.setBackgroundResource(R.drawable.menu4_selected);
			tv4.setTextColor(getResources().getColor(R.color.color_00CD00));
			break;
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		if (resultCode != RESULT_OK) { // 此处的 RESULT_OK 是系统自定义得一个常量
			Log.e("wulianshu", "ActivityResult resultCode error");
			return;
		}
		if (requestCode == fragment4.IMAGE_CODE) {
			// 外界的程序访问ContentProvider所提供数据 可以通过ContentResolver接口
			ContentResolver resolver = getContentResolver();
			// 此处的用于判断接收的Activity是不是你想要的那个
			if (requestCode == fragment4.IMAGE_CODE) {
				try {
					Uri originalUri = data.getData(); // 获得图片的uri
					final Bitmap bitmap = MediaStore.Images.Media.getBitmap(resolver, originalUri);
					// 显得到bitmap图片
					// 这里开始的第二部分，获取图片的路径：
					String[] proj = { MediaStore.Images.Media.DATA };
					// 好像是android多媒体数据库的封装接口，具体的看Android文档
					Cursor cursor = managedQuery(originalUri, proj, null, null, null);
					// 按我个人理解 这个是获得用户选择的图片的索引值
					int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
					// 将光标移至开头 ，这个很重要，不小心很容易引起越界
					cursor.moveToFirst();
					// 最后根据索引值获取图片路径
					String path = cursor.getString(column_index);
					if (bitmap != null) {
						final CUserInfo userInfo = AppCache.getInstance().getUseInfo();
						ThreadPoolAgent.executeAsynTask(new Runnable() {

							@Override
							public void run() {
								if (userInfo != null) {
									sendEmptydMessage(MSG_SHOW_PROGRESS_DIALOG);
									HashMap<String, String> params = new HashMap<String, String>();
									params.put("telephone", userInfo.getTelephone());
									HashMap<String, byte[]> bytes = new HashMap<String, byte[]>();
									bytes.put("icons", BitmapUtil.bitmap2Bytes(bitmap));
									NetModel netModel = NetworkAgent.request(params,
											ConstanceUtil.REQUEST_SAVE_USER_IMAGE, bytes);
									Message msg = new Message();
									msg.what = MSG_UPDATE_USER_ICON;
									msg.obj = netModel;
									sendMessage(msg);
								}
								bitmap.recycle();
							}
						});

					}
				} catch (IOException e) {
					Log.e("wulianshu", e.toString());

				}

			}
		} else if (requestCode == 1000) {
			cUserInfo = (CUserInfo) data.getSerializableExtra("cuserinfo");
			fragment4.initData();
		}
	}

	@Override
	public void onBackPressed() {
		showNoticeDialog(getString(R.string.exit_notice_title), getString(R.string.exit_notice_message),
				new OnNoticeDialogListener() {

					@Override
					public void onSure() {
						finish();
					}

					@Override
					public void onCancel() {
					}
				});
	}

	@Override
	protected void onHandleMessage(Message msg) {
		switch (msg.what) {
		case MSG_UPDATE_USER_ICON: {
			sendEmptydMessage(MSG_HIDE_PROGRESS_DIALOG);
			if (fragment4 != null) {
				NetModel netModel = (NetModel) msg.obj;
				if (netModel != null) {
					try {
						if (netModel.getCode() == ConstanceUtil.REQUEST_SUCCESS) {
							CUserInfo userInfo = JsonUtil.parseObject(netModel.getContent(), CUserInfo.class);
							AppCache.getInstance().saveUserInfo(userInfo);
						}
					} catch (Exception e) {
					}
				}
				fragment4.initData();
			}
			break;
		}
		case MSG_SHOW_PROGRESS_DIALOG: {
			showProgressDialog(getString(R.string.update_loading));
			break;
		}
		case MSG_HIDE_PROGRESS_DIALOG: {
			hideProgressDialog();
			break;
		}
		default:
			break;
		}
	}

	class MainBroadcastReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context arg0, Intent arg1) {
			// TODO Auto-generated method stub
			// CTalkMessage cTalkMessage = (CTalkMessage)
			// arg1.getSerializableExtra("talkmessage");
			// ToastUtil.showShortToast(MainActivity.this, "MainActivity接收到消息了:"
			// + cTalkMessage.getMessage_content());
		}
	}

	public void RegisterBroadCastReceiver() {
		IntentFilter filter = new IntentFilter();
		filter.addAction(ConstanceUtil.MAIN_ACTIVITY_BROAD);
		registerReceiver(mainBroadcastReceiver, filter);
	}

	public void UnregisterBroadCastReceiver() {
		unregisterReceiver(mainBroadcastReceiver);
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		RegisterBroadCastReceiver();
		super.onStart();
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		UnregisterBroadCastReceiver();
		CommentResponseListener listener =new CommentResponseListener ();
		HttpApi.unRegisterDevice(cUserInfo.getTelephone(),listener , listener);
		super.onDestroy();
	}

	class CommentResponseListener
			implements com.android.volley.Response.Listener<String>, com.android.volley.Response.ErrorListener {

		@Override
		public void onResponse(String response) {
			// TODO Auto-generated method stub
			NetModel netModel = JsonUtil.parseObject(response, NetModel.class);
			// ToastUtil.showShortToast(HospitalClientApplication.getmInstance(),
			// netModel.getContent());
		}

		@Override
		public void onErrorResponse(VolleyError error) {
			// TODO Auto-generated method stub
			ToastUtil.showShortToast(HospitalClientApplication.getmInstance(), "网络异常");

		}
	}

}
